package WZL.newba;

import java.util.Stack;


public class Jisuan {

    private final char ADD = '+';

    private final char SUBTRACT = '-';

    private final char MULTIPLY = '*';

    private final char DIVIDE = '/';

    private Stack<Integer> stack;

    public Jisuan(){
        stack = new Stack<Integer>();
    }


    public int evaluate(String expr){
        int op1,op2,result=0;
        String token;
        //将字符串分解,\s 匹配任何空白字符，包括空格、制表符、换页符等。
        String[] tokenizer = expr.split("\\s");
        for (int x = 0; x < tokenizer.length; x++){
            System.out.print(tokenizer[x]+" ");//输出---显示输入的表达式
            token = tokenizer[x];
            if(isOperator(token)){//判断是操作符，则出栈两个操作数
                op2 = (stack.pop()).intValue();
                op1 = (stack.pop()).intValue();
                result = evalSingleOp (token.charAt(0),op1,op2);//计算结果
                stack.push(new Integer(result));//把计算结果压入栈中
            }else {
                stack.push(new Integer(Integer.parseInt(token)));//压入操作数
            }
        }
        return result;
    }

    private int evalSingleOp(char operation, int op1, int op2) {
        int result = 0;
        switch(operation)
        {
            case ADD:
                result = op1+op2;
                break;
            case SUBTRACT:
                result = op1-op2;
                break;
            case MULTIPLY:
                result = op1*op2;
                break;
            case DIVIDE:
                result = op1/op2;
                break;
        }
        return result;
    }

    private boolean isOperator(String token) {

        return (token.equals("+")||token.equals("-")||
                token.equals("*")||token.equals("/"));
    }
}
